package com.itzb.asone.controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.itzb.asone.application.BaseController;
import com.itzb.asone.fileserver.IFileServer;
import com.itzb.asone.fileserver.model.FSResult;
import com.itzb.asone.system.service.IMessageService;
import com.itzb.asone.utils.GitId;
import com.itzb.asone.utils.JsonResult;

@Controller
@RequestMapping(value = "fileupload")
public class UploaderController extends BaseController {
	
	private Logger logger = Logger.getLogger(getClass()); 
	
	
	@Autowired
	private IFileServer fileServer;
	@Autowired
	private IMessageService messageService;

	@ResponseBody
	@RequestMapping(value = "/upload", method = { RequestMethod.POST })
	public String upload(@RequestParam(value = "file") MultipartFile uploadFile,HttpServletRequest request,HttpServletResponse response) {
		JsonResult jsonResult = JsonResult.newInstance();
		String realPath = request.getSession().getServletContext().getRealPath("/upload");
		try{
			// 文件原名称
			String fileName = uploadFile.getOriginalFilename();
			String fileType = fileName.split("\\.")[1];
			fileName = GitId.getFileName() + "." + fileType;
			File file = new File(realPath, fileName);
			if(!file.exists()){  
				file.mkdirs();  
	        }
			uploadFile.transferTo(file);
			FSResult fsResult = fileServer.uploadFile(file.getPath(), fileName);
			
			
			if (file.isFile() && file.exists()) {  
		        file.delete();  
		    } 
			
			if(fsResult.getSuccess()){
				jsonResult.addContent("fileUrl", fsResult.getList().get(0).getFilePath());
				jsonResult.addContent("fileName", fsResult.getList().get(0).getFileName());
				jsonResult.addContent("fileId", fsResult.getId());
				jsonResult.declareSuccess();
			} else {
				jsonResult.declareFailure();
			}
			logger.info(jsonResult);
			
			
		} catch (Exception e){
			e.printStackTrace();
		}
		
		
		return JSONObject.toJSON(jsonResult).toString();
	}
}
